package com.ybxx.system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import com.ybxx.core.service.impl.BaseServiceImpl;
import com.ybxx.system.dao.PermissionDao;
import com.ybxx.system.model.Permission;
import com.ybxx.system.model.User;
import com.ybxx.system.service.PermissionService;

public class PermissionServiceImpl extends BaseServiceImpl<Permission>
		implements PermissionService {
	private PermissionDao permissionDao;
	public PermissionServiceImpl(PermissionDao permissionDao){
		super(permissionDao);
		this.permissionDao=permissionDao;
	}
	/**依据登录名加载参数权限数据*/
	public List<Permission> load(String loginid){
		List<Permission> permissions=null;
		String hql="from User u left join fetch u.permissions p left join fetch p.childs " +
				"where u.loginid='"+loginid+"' and p.parent.pid is null order by p.seq";
		try{
			User user=(User)permissionDao.findUnique(hql, null);
			if(user!=null){
				permissions=new ArrayList<Permission>(user.getPermissions());
				Collections.sort(permissions,new Comparator<Permission>(){
					public int compare(Permission o1, Permission o2) {
						if(o1.getSeq()<o2.getSeq()){
							return -1;
						}else if(o1.getSeq()==o2.getSeq()){
							return 0;
						}else{
							return 1;
						}
					}});
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			return permissions;
		}
	}
	
	@Override
	public List<Permission> getAll() {
		List<Permission> permissions=null;
		String hql="select distinct p from Permission p left join fetch p.childs " +
					"where p.parent.pid is null";
		permissions=permissionDao.findByHql(hql, null);
		return permissions;
	}
	
	public List<Permission> loadParent() {
		List<Permission> permissions=null;
		String hql="from Permission p " +
					"where p.parent.pid is null";
		permissions=permissionDao.findByHql(hql, null);
		return permissions;
	}
	public List<Permission> queryUserPermission(String loginid){
		String sql="select p.pid,fid,pname,case when loginid is null then false else true end as checked " +
				"from tbl_system_permission p left join (select * from tbl_system_user_permission where loginid='"+loginid+"') up " +
				"on p.pid=up.pid";
		return permissionDao.queryUserPermission(sql);
	}
	

}
